package cn.bonoon.kernel.util;

import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

public final class DESUtil extends CryptoUtil{
	private static final String DES = "DES";
	public Key getKey(String strKey) {
		try {
			KeyGenerator _generator = KeyGenerator.getInstance(DES);
			_generator.init(new SecureRandom(strKey.getBytes()));
			Key key = _generator.generateKey();
			_generator = null;
			return key;
		} catch (Exception e) {
			throw new RuntimeException(
					"Error initializing SqlMap class. Cause: " + e);
		}
	}

	public Key getKey(byte[] byteKey) throws Exception {
		// 创建一个空的8位字节数组（默认值为0）
		byte[] arrB = new byte[8];
		// 将原始字节数组转换为8位
		for (int i = 0; i < byteKey.length && i < arrB.length; i++) {
			arrB[i] = byteKey[i];
		}
		// 生成密钥
		Key key = new SecretKeySpec(arrB, DES);
		return key;
	}

	public byte[] encrypt(byte[] source, String strKey) throws Throwable {
		return crypto(Cipher.ENCRYPT_MODE, strKey, source);
	}

	public byte[] crypto(int opmode, String strKey, byte[] source)
			throws Throwable {
		Cipher cipher = Cipher.getInstance(DES);
		Key key = getKey(strKey);
		cipher.init(opmode, key);
		return cipher.doFinal(source);
	}

	public byte[] decrypt(byte[] source, String strKey) throws Throwable {
		return crypto(Cipher.DECRYPT_MODE, strKey, source);
	}
}
